package com.gmcc.docmanager.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.gmcc.docmanager.R;

import android.content.Context;

public class ErrorCodeUtils {

	private static String unknowError = "";

	private static Map<String, Map<String, String>> errorCodeMapping;

	private final static String ERROR_CODE_FILE_NAME = "error_code_mapping.xml";

	public static String getErrorDescription(String errorType, String errorCode) {
		if (errorCodeMapping.isEmpty()) {
			return unknowError;
		}
		Map<String, String> errorMap = errorCodeMapping.get(errorType);
		if (errorMap == null) {
			return unknowError;
		}
		String errorStr = errorMap.get(errorCode);
		if (errorStr == null) {
			return unknowError;
		}
		return errorStr;
	}

	public static void buildErrorCodeMapping(Context context) {
		errorCodeMapping = new HashMap<String, Map<String, String>>();
		unknowError = context.getString(R.string.unknow_error);
		InputStream is = null;
		try {
			is = context.getAssets().open(ERROR_CODE_FILE_NAME);
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder db = factory.newDocumentBuilder();
			Document document = db.parse(is);
			Element rootElement = document.getDocumentElement();
			NodeList typeLists = rootElement.getElementsByTagName("error");
			for (int i = 0; i < typeLists.getLength(); i++) {
				Element type = (Element) typeLists.item(i);
				String typeName = type.getAttribute("name");
				NodeList errorLists = type.getElementsByTagName("code");
				Map<String, String> errorMapping = new HashMap<String, String>();
				for (int j = 0; j < errorLists.getLength(); j++) {
					Element error = (Element) errorLists.item(j);
					String errorCode = error.getAttribute("name");
					String errorDescription = error.getAttribute("value");
					errorMapping.put(errorCode, errorDescription);
				}
				errorCodeMapping.put(typeName, errorMapping);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
